<template>
	<view class="video-container">
		<video ref="videoRef" controls autoplay playsinline class="video-element"></video>
	</view>
</template>

<script>
import flvjs from 'flv.js';

export default {
	name: 'FlvPlayer',
	props: {
		streamUrl: {
			type: String,
			default: ''
		},
		isLive: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			flvPlayer: null
		};
	},
	mounted() {
		this.initPlayer();
	},
	beforeDestroy() {
		this.destroyPlayer();
	},
	methods: {
		initPlayer(url) {
			if (!flvjs.isSupported()) {
				console.error('当前浏览器不支持 flv.js');
				return;
			}

			// 获取原生video元素的核心修正代码
			const videoComponent = this.$refs.videoRef;
			if (!videoComponent) return;

			// H5环境下获取内部原生video标签
			let videoElement;
			if (process.env.VUE_APP_PLATFORM === 'h5') {
				const container = videoComponent.$el;
				videoElement = container.querySelector('video');
				if (!videoElement) {
					console.error('找不到原生video元素');
					return;
				}
			} else {
				console.warn('非H5环境需改用web-view方案');
				return;
			}

			this.flvPlayer = flvjs.createPlayer({
				type: 'flv',
				url: url ? url : this.streamUrl,
				isLive: this.isLive,
				cors: true
			});

			this.flvPlayer.attachMediaElement(videoElement);
			this.flvPlayer.load();
			this.flvPlayer.play().catch((err) => {
				console.log(err);
			});

			this.flvPlayer.on(flvjs.Events.ERROR, (errorType, errorDetail) => {
				console.error('播放错误:', errorType, errorDetail);
			});
		},
		destroyPlayer() {
			if (this.flvPlayer) {
				this.flvPlayer.pause(); // 停止播放
				this.flvPlayer.unload(); // 卸载资源
				this.flvPlayer.detachMediaElement(); // 解绑元素
				this.flvPlayer.destroy(); // 销毁实例
				this.flvPlayer = null;
			}
		}
	}
};
</script>

<style scoped lang="scss">
.video-container {
	width: 100%;
	height: 500rpx;
}
.video-element {
	width: 100%;
	height: 100%;
}

</style>
